package sdk.login.tvos.com.surfaceview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * Created by sufutian on 2016/9/30/14:30.
 */
public class SurfaceViewDraw extends SurfaceView implements SurfaceHolder.Callback,Runnable{

    private SurfaceHolder mSurfaceHolder;
    private Canvas canvas;
    private boolean isDraw;
    private Paint paint;
    private Path path;
    public SurfaceViewDraw(Context context) {
        super(context);
        initView();
    }

    public SurfaceViewDraw(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public SurfaceViewDraw(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    private void initView() {
        mSurfaceHolder=getHolder();
        mSurfaceHolder.addCallback(this);
        setFocusable(true);
        setFocusableInTouchMode(true);
        setKeepScreenOn(true);

        paint=new Paint();
        paint.setColor(Color.RED);
        paint.setAntiAlias(true);
        path=new Path();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        isDraw = true;
        //开启子线程
        new Thread(this).start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isDraw=false;
    }

    int x;
    int y;
    float left;
    float right;
    float top;
    float bottom;
    @Override
    public void run() {
        while(isDraw){
            draw();
            x += 4;
            y = (int) (100 * Math.sin(x * 2 * Math.PI / 180) + 400);
            path.addCircle(x,y,10, Path.Direction.CCW);
            path.moveTo(x,y);
        }
    }

    private void draw() {
        try {
            canvas = mSurfaceHolder.lockCanvas();
            canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
            canvas.drawColor(Color.WHITE);
            canvas.drawPath(path,paint);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(canvas != null)
                //将该方法放到finally代码块中，来保证每次都能将画布内容进行提交
                mSurfaceHolder.unlockCanvasAndPost(canvas);
        }

    }

    private void cycle() {
        x++;
    }
}
